package com.penghaisoft.microwms.product.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.dto.ProHandInDto;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.dto.TransResult;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.common.service.BaseService;
import com.penghaisoft.microwms.common.wms.model.ProHandIn;
import com.penghaisoft.microwms.common.wms.model.ProHandInSn;
import com.penghaisoft.microwms.common.wms.model.ProStorageSn;
import com.penghaisoft.microwms.product.dao.ProHandInMapper;
import com.penghaisoft.microwms.product.dao.ProHandInSnMapper;
import com.penghaisoft.microwms.product.dao.ProStorageSnMapper;
import com.penghaisoft.microwms.product.service.IProHandInService;

/**
 * @Description 成品手工入库表
 * @author luoteng
 * @date 2018年6月12日 下午3:02:07
 * @version 1.0
 */
@Service("proHandInService")
public class ProHandInServiceImpl extends BaseService implements
		IProHandInService {
	@Resource
	private ProHandInMapper proHandInMapper;
	
	@Resource
	private ProHandInSnMapper proHandInSnMapper;
	
	@Resource
	private ProStorageSnMapper proStorageSnMapper;

	/**
	 * 新增记录
	 * 
	 * @param baseResource
	 * @return
	 */
	@Override
	public Resp create(ProHandIn proHandIn) {
		proHandInMapper.create(proHandIn);
		return success();
	}

	/**
	 * 删除记录（逻辑删除）
	 * 
	 * @param baseResource
	 * @return
	 */
	@Override
	public Resp delete(ProHandIn proHandIn) {
		proHandInMapper.delete(proHandIn);
		return success();
	}

	/**
	 * 查询列表
	 * 
	 * @param pager
	 * @param baseResource
	 * @return
	 */
	@Override
	public Pager<ProHandIn> findListByCondition(int page, int rows,
			ProHandIn condition) {
		Pager<ProHandIn> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);
		condition.preQuery();
		long size = proHandInMapper.queryCount(condition);
		List<ProHandIn> records = new ArrayList<ProHandIn>();
		if (size > 0) {
			records = proHandInMapper.queryList(pager, condition);
		}
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}

	/**
	 * 查询单条
	 * 
	 * @param id
	 * @return
	 */
	@Override
	public ProHandIn findById(String id) {
		return proHandInMapper.queryById(id);
	}

	/**
	 * 修改记录
	 * 
	 * @param baseResource
	 * @return
	 */
	@Override
	public Resp update(ProHandIn proHandIn) {
		proHandInMapper.updateBySelect(proHandIn);
		return success();
	}
	
	/** 
	 * @Title batchInsert
	 * @Description 手工入库批量插入
	 * @author luoteng
	 * @date 2018年6月13日:下午3:56:40
	 * @param list
	 * @param handInNo
	 * @param loginName
	 * @return
	 */
	@Transactional
	@Override
	public Resp batchInsert(List<ProHandIn> list, String handInNo, String loginName) {
		Date now = new Date();
		HashSet<String> allSet = new HashSet<String>();
    	for(int i = 0 ; i < list.size(); i ++){
    		ProHandIn tmpInsertOb = list.get(i);
    		
    		StringBuffer uniqueStr = new StringBuffer("");
    		uniqueStr.append(tmpInsertOb.getModel());
    		uniqueStr.append(tmpInsertOb.getModelType());
    		if(allSet.contains(uniqueStr.toString())){
    			Resp resp = new Resp();
    			resp.setCode(Constant.FAIL);
    			resp.setMsg("选择的型号、型号类型重复");
    			return resp;
    		}else{
    			allSet.add(uniqueStr.toString());
    		}
    	}
    	
    	for(int i = 0 ; i < list.size(); i ++){
    		ProHandIn tmpInsertOb = list.get(i);
    		
//    		合同编号、型号、型号类型、需求数量 页面传递的参数已经提供
    		tmpInsertOb.setHandInNo(handInNo);
//    		0新建 1入库中 2入库完成
    		tmpInsertOb.setHandInStatus("0");
    		tmpInsertOb.setActiveFlag("1");
    		tmpInsertOb.setGmtCreate(now);
    		tmpInsertOb.setCreateBy(loginName);
    		
    		proHandInMapper.create(tmpInsertOb);
    	}
    	
		return success();
	}
	
	/** 
	 * @Title queryListByAny
	 * @Description 根据手工入库单号查询手工入库数据
	 * @author luoteng
	 * @date 2018年6月13日:下午4:49:07
	 * @param condition
	 * @return
	 */
	@Override
	public List<ProHandIn> queryListByAny(ProHandIn condition){
		return proHandInMapper.queryByAny(condition);
	}
	
	/** 
	 * @Title loadBill
	 * @Description 手工入库提单
	 * @author luoteng
	 * @date 2018年6月14日:上午10:20:20
	 * @param handInNo
	 * @return
	 */
	@Override
	public Resp loadBill(String handInNo){
		Resp resp = new Resp();
		
		ProHandIn proHandIn = new ProHandIn();
		proHandIn.setHandInNo(handInNo);
		proHandIn.setActiveFlag("1");
		
		List<ProHandIn> list = proHandInMapper.queryByAny(proHandIn);
		if(list == null || list.isEmpty()){
			resp.setCode(Constant.FAIL);
			resp.setMsg("该手工出库单号不存在");
		}else{
			Boolean flag_all_2 = true;
			for(ProHandIn tmp : list){
//				0新建 1入库中 2入库完成
				if(!"2".equals(tmp.getHandInStatus())){
					flag_all_2 = false;
				}
			}
			
			if(flag_all_2){
				resp.setCode(Constant.FAIL);
				resp.setMsg("该手工出库单号已经发货完成！");
				return resp;
			}
			
			resp.setCode(Constant.SUCCESS);
			resp.setMsg("扫描成功");
		}
		
		return resp;
	}
	
	/** 
	 * @Title handInScanBarcode
	 * @Description 手工入库扫码
	 * @author luoteng
	 * @date 2018年6月14日:下午2:01:42
	 * @param proHandInDto
	 * @return
	 */
	@Transactional
	@Override
	public TransResult handInScanBarcode(ProHandInDto proHandInDto){
		TransResult result = new TransResult();
        result.setCode(Constant.SUCCESS);
        
        Date now = new Date();
        
        ProStorageSn proStorageSn = new ProStorageSn();
    	proStorageSn.setBarcode(proHandInDto.getBarcode());
    	proStorageSn.setActiveFlag("1");
    	
    	List<ProStorageSn> storageList = proStorageSnMapper.queryByAny(proStorageSn);
    	if(storageList == null || storageList.isEmpty()){
        	result.setCode(Constant.FAIL);
            result.setMsg("该成品条码不存在。");
            return result;
        }else if(storageList.size() > 1){
        	result.setCode(Constant.FAIL);
            result.setMsg("该成品条码重复。");
            return result;
        }else{
        	ProStorageSn storageSnTmp = storageList.get(0);
        	
//        	0：可用 1：冻结 2：已出库 3：抽检冻结
        	if(storageSnTmp.getBarcodeStatus() == null){
        		result.setCode(Constant.FAIL);
        		result.setMsg("该条码状态为空。");
                return result;
        	}else if(storageSnTmp.getBarcodeStatus().equals("2")){
        		result.setCode(Constant.FAIL);
        		result.setMsg("该条码已出库。");
                return result;
        	}else if(storageSnTmp.getBarcodeStatus().equals("1") || storageSnTmp.getBarcodeStatus().equals("3")){
        		result.setCode(Constant.FAIL);
        		result.setMsg("该条码已冻结。");
                return result;
        	}else if(storageSnTmp.getBarcodeStatus().equals("0")){
        		ProHandInSn proHandInSn = new ProHandInSn();
        		proHandInSn.setBarcode(proHandInDto.getBarcode());
        		proHandInSn.setActiveFlag("1");
        		
        		List<ProHandInSn> handInSnList = proHandInSnMapper.queryByAny(proHandInSn);
        		if(handInSnList != null && !handInSnList.isEmpty()){
        			result.setCode(Constant.FAIL);
        			result.setMsg("该条码已经扫描，不能再次扫描!");
					return result;
        		}else{
        			ProHandIn proHandIn = new ProHandIn();
        			proHandIn.setHandInNo(proHandInDto.getHandInNo());
        			proHandIn.setContractNo(proHandInDto.getContractNo());
        			proHandIn.setModel(storageSnTmp.getModel());
//        			proHandIn.setModelType(storageSnTmp.getModelType());
        			proHandIn.setActiveFlag("1");
        			
        			List<ProHandIn> handInList = proHandInMapper.queryByAny(proHandIn);
        			if (handInList == null || handInList.isEmpty()) {
        				result.setCode(Constant.FAIL);
    					result.setMsg("该条码不是手工出库单所需型号!");
    					return result;
    				}else{
    					ProHandIn handInTmp = handInList.get(0);
//    					if(!handInTmp.getContractNo().equals(storageSnTmp.getContractNo())){
//    						result.setCode(Constant.FAIL);
//        					result.setMsg("该条码合同号（" + storageSnTmp.getContractNo() + "）与该手工出库单的合同号（" + handInTmp.getContractNo() + "）不相同!");
//        					return result;
//    					}
    					List<ProHandIn> rtnList = new ArrayList<ProHandIn>();
    					
    					// 需求数量
    					BigDecimal requireAmount = handInTmp.getRequireAmount() ==null ? BigDecimal.ZERO : handInTmp.getRequireAmount();
    					// 已发数量
    					BigDecimal realAmount = handInTmp.getRealAmount() == null ? BigDecimal.ZERO : handInTmp.getRealAmount();
    					
//    					C-STG-L:塑套钢-螺旋钢管 C-STG-W:塑套钢-无缝钢管 C-GTG-L:钢套钢-螺旋钢管 C-GTG-W:钢套钢-无缝钢管 C-BLG-L:玻璃钢-螺旋钢管 C-BLG-W:玻璃钢-无缝钢管 C-W:弯头 C-ST:三通 C-BJ:变径 C-G:固定支架
    					String modelType = handInTmp.getModelType() == null ? "" : handInTmp.getModelType();
    					
    					if (realAmount.compareTo(requireAmount) == 0
								|| requireAmount.compareTo(realAmount) < 0) {
							result.setCode(Constant.FAIL);
							result.setMsg("该型号已经扫码完成，无需继续扫码!");
							return result;
						} else {
//							0新建 1入库中 2入库完成
							handInTmp.setHandInStatus("1");
							handInTmp.setLastModifiedBy(proHandInDto.getLoginName());
							handInTmp.setGmtModified(now);
							
//							更新数量的sql 去掉realAmout的更新
							handInTmp.setRealAmount(null);
							
//							if(modelType.equals(Constant.PRO_MODEL_TYPE_WT) || modelType.equals(Constant.PRO_MODEL_TYPE_ST) 
//	    							|| modelType.equals(Constant.PRO_MODEL_TYPE_BJ) || modelType.equals(Constant.PRO_MODEL_TYPE_G)){
//								handInTmp.setRealAmountAdd(new BigDecimal(1));
//								realAmount = realAmount.add(new BigDecimal(1));
//	    					}else{
//								handInTmp.setRealAmountAdd(storageSnTmp.getAmount());
//								realAmount = realAmount.add(storageSnTmp.getAmount());
//	    					}
						}
    					
    					Integer rtVal = proHandInMapper.updateBySelect(handInTmp);
						if(rtVal != 1){
							throw new RuntimeException("扫描条码失败，更新条数存在问题!");
						}
						
//						该实发数量只是提供给手持显示，后台sql加数量
						handInTmp.setRealAmount(realAmount);
//						返回给手持数据
						rtnList.add(handInTmp);
						result.setList(rtnList);
						
						ProHandIn yzOb = new ProHandIn();
						yzOb.setHandInId(handInTmp.getHandInId());
						List<ProHandIn> yzList = proHandInMapper.queryByAny(yzOb);
						
						BigDecimal maxRealAmout = requireAmount.add(Constant.PRO_STATIC_METER);
						if(modelType.equals(Constant.PRO_MODEL_TYPE_WT) || modelType.equals(Constant.PRO_MODEL_TYPE_ST) 
    							|| modelType.equals(Constant.PRO_MODEL_TYPE_BJ) || modelType.equals(Constant.PRO_MODEL_TYPE_G)){
							if(yzList.get(0).getRequireAmount().compareTo(yzList.get(0).getRealAmount()) < 0 ){
								throw new RuntimeException("该型号已经扫码完成，无需继续扫码!");
							}
    					}else{
    						if(maxRealAmout.compareTo(yzList.get(0).getRealAmount()) < 0){
    							throw new RuntimeException("该型号已经扫码完成，无需继续扫码!");
    						}
    					}
						
						
						ProHandInSn handInSnInsertOb = new ProHandInSn();
						handInSnInsertOb.setHandInNo(handInTmp.getHandInNo());
						handInSnInsertOb.setContractNo(handInTmp.getContractNo());
						handInSnInsertOb.setBarcode(proHandInDto.getBarcode());
						handInSnInsertOb.setModel(handInTmp.getModel());
						handInSnInsertOb.setModelDesc(handInTmp.getModelDesc());
						handInSnInsertOb.setModelType(handInTmp.getModelType());
						handInSnInsertOb.setType(handInTmp.getType());
//						handInSnInsertOb.setAmount(storageSnTmp.getAmount());
						handInSnInsertOb.setUnit(storageSnTmp.getUnit());
						handInSnInsertOb.setWlCode(storageSnTmp.getWlCode());
						handInSnInsertOb.setActiveFlag("1");
						handInSnInsertOb.setGmtCreate(now);
						handInSnInsertOb.setCreateBy(proHandInDto.getLoginName());
						
						proHandInSnMapper.create(handInSnInsertOb);
						
//						List<ProHandInSn> handInSnYzList = proHandInSnMapper.queryByAny(proHandInSn);
//						if(handInSnYzList.size() > 1){
//							throw new RuntimeException();
//						}
						
//						0：可用 1：冻结 2：已出库 3：抽检冻结
						storageSnTmp.setBarcodeStatus("2");
						storageSnTmp.setLastModifiedBy(proHandInDto.getLoginName());
						storageSnTmp.setGmtModified(now);
						
						Integer rtVal1 = proStorageSnMapper.updateByBarcodeStatus0(storageSnTmp);
						if(rtVal1 != 1){
							throw new RuntimeException("当前条码已经出库，或者被冻结！");
						}
    				}
        		}
        		
        	}
        }
        
        return result;
	}
	
	/** 
	 * @Title handInDelBarcode
	 * @Description 手工入库删除条码
	 * @author luoteng
	 * @date 2018年6月14日:下午5:25:02
	 * @param proHandInDto
	 * @return
	 */
	@Transactional
	@Override
	public TransResult handInDelBarcode(ProHandInDto proHandInDto){
		TransResult result = new TransResult();
        result.setCode(Constant.SUCCESS);
        
        Date now = new Date();
        
        ProStorageSn proStorageSn = new ProStorageSn();
    	proStorageSn.setBarcode(proHandInDto.getBarcode());
//    	0：可用 1：冻结 2：已出库 3：抽检冻结
    	proStorageSn.setBarcodeStatus("2");
    	proStorageSn.setActiveFlag("1");
    	
    	List<ProStorageSn> storageList = proStorageSnMapper.queryByAny(proStorageSn);
    	if(storageList == null || storageList.isEmpty()){
        	result.setCode(Constant.FAIL);
            result.setMsg("该成品条码不存在。");
            return result;
        }else if(storageList.size() > 1){
        	result.setCode(Constant.FAIL);
            result.setMsg("该成品条码重复。");
            return result;
        }else{
        	ProStorageSn storageSnTmp = storageList.get(0);
        	
        	ProHandInSn proHandInSn = new ProHandInSn();
        	proHandInSn.setHandInNo(proHandInDto.getHandInNo());
    		proHandInSn.setBarcode(proHandInDto.getBarcode());
    		proHandInSn.setActiveFlag("1");
    		
    		List<ProHandInSn> handInSnList = proHandInSnMapper.queryByAny(proHandInSn);
    		if(handInSnList == null || handInSnList.isEmpty()){
    			result.setCode(Constant.FAIL);
    			result.setMsg("该条码未扫描!");
				return result;
    		}else{
    			ProHandInSn proHandInSnTmp = handInSnList.get(0);
    			ProHandIn proHandIn = new ProHandIn();
    			proHandIn.setHandInNo(proHandInDto.getHandInNo());
//    			proHandIn.setContractNo(storageSnTmp.getContractNo());
    			proHandIn.setModel(storageSnTmp.getModel());
//    			proHandIn.setModelType(storageSnTmp.getModelType());
    			proHandIn.setActiveFlag("1");
    			
    			List<ProHandIn> handInList = proHandInMapper.queryByAny(proHandIn);
    			if (handInList == null || handInList.isEmpty()) {
    				result.setCode(Constant.FAIL);
					result.setMsg("该条码不是手工出库单所需型号!");
					return result;
				}else{
					ProHandIn handInTmp = handInList.get(0);
					List<ProHandIn> rtnList = new ArrayList<ProHandIn>();
					
					// 需求数量
					BigDecimal requireAmount = handInTmp.getRequireAmount() ==null ? BigDecimal.ZERO : handInTmp.getRequireAmount();
					// 已发数量
					BigDecimal realAmount = handInTmp.getRealAmount() == null ? BigDecimal.ZERO : handInTmp.getRealAmount();
					
//					C-STG-L:塑套钢-螺旋钢管 C-STG-W:塑套钢-无缝钢管 C-GTG-L:钢套钢-螺旋钢管 C-GTG-W:钢套钢-无缝钢管 C-BLG-L:玻璃钢-螺旋钢管 C-BLG-W:玻璃钢-无缝钢管 C-W:弯头 C-ST:三通 C-BJ:变径 C-G:固定支架
					String modelType = handInTmp.getModelType() == null ? "" : handInTmp.getModelType();
					
//					0新建 1入库中 2入库完成
					handInTmp.setHandInStatus("1");
					handInTmp.setLastModifiedBy(proHandInDto.getLoginName());
					handInTmp.setGmtModified(now);
					
//					if(modelType.equals(Constant.PRO_MODEL_TYPE_WT) || modelType.equals(Constant.PRO_MODEL_TYPE_ST) 
//							|| modelType.equals(Constant.PRO_MODEL_TYPE_BJ) || modelType.equals(Constant.PRO_MODEL_TYPE_G)){
//						handInTmp.setRealAmountDel(new BigDecimal(1));
//						realAmount = realAmount.subtract(new BigDecimal(1));
//					}else{
//						handInTmp.setRealAmountDel(storageSnTmp.getAmount());
//						realAmount = realAmount.subtract(storageSnTmp.getAmount());
//					}
					
					Integer rtVal = proHandInMapper.updateBySelect(handInTmp);
					if(rtVal != 1){
						throw new RuntimeException("删除条码失败，更新条数存在问题!");
					}
					
//					该实发数量只是提供给手持显示，后台sql加数量
					handInTmp.setRealAmount(realAmount);
//					返回给手持数据
					rtnList.add(handInTmp);
					result.setList(rtnList);
					
					proHandInSnTmp.setActiveFlag("0");
					proHandInSnTmp.setLastModifiedBy(proHandInDto.getLoginName());
					proHandInSnTmp.setGmtModified(now);
					
					Integer rtVal1 = proHandInSnMapper.updateBySelect(proHandInSnTmp);
					if(rtVal1 != 1){
						throw new RuntimeException("删除条码失败，更新条数存在问题!");
					}
					
//					0：可用 1：冻结 2：已出库 3：抽检冻结
					storageSnTmp.setBarcodeStatus("0");
					storageSnTmp.setLastModifiedBy(proHandInDto.getLoginName());
					storageSnTmp.setGmtModified(now);
					
					Integer rtVal2 = proStorageSnMapper.updateByBarcodeStatus2(storageSnTmp);
					if(rtVal2 != 1){
						throw new RuntimeException("删除条码失败，更新条数存在问题!");
					}
				}
    		}
        }
        
        return result;
	}
	
	/** 
	 * @Title handInComplete
	 * @Description 确认完成
	 * @author luoteng
	 * @date 2018年6月15日:下午3:03:22
	 * @param proHandInDto
	 * @return
	 */
	@Transactional
	@Override
	public TransResult handInComplete(ProHandInDto proHandInDto){
		TransResult result = new TransResult();
        result.setCode(Constant.SUCCESS);
        
        Date now = new Date();
        
		ProHandIn proHandIn = new ProHandIn();
		proHandIn.setHandInNo(proHandInDto.getHandInNo());
		proHandIn.setActiveFlag("1");
		
		List<ProHandIn> handInList = proHandInMapper.queryByAny(proHandIn);
		if(handInList == null || handInList.isEmpty()){
			result.setCode(Constant.FAIL);
			result.setMsg("该手工出库单不存在!");
			return result;
		}else{
			for(ProHandIn tmp : handInList){
				// 需求数量
				BigDecimal requireAmount = tmp.getRequireAmount() ==null ? BigDecimal.ZERO : tmp.getRequireAmount();
				// 已发数量
				BigDecimal realAmount = tmp.getRealAmount() == null ? BigDecimal.ZERO : tmp.getRealAmount();
				
				BigDecimal maxRealAmout = Constant.PRO_STATIC_METER.add(requireAmount);
								
				if(requireAmount.compareTo(realAmount) > 0){
					result.setCode(Constant.FAIL);
					result.setMsg("该手工出库单未扫码完毕!");
					return result;
				}else if(maxRealAmout.compareTo(realAmount) < 0){
					result.setCode(Constant.FAIL);
					result.setMsg("该手工出库单扫码数量超过需求数量!");
					return result;
				}
			}
			
			ProHandInSn snTmp = new ProHandInSn();
			snTmp.setHandInNo(proHandInDto.getHandInNo());
//			 查询手工入库单 开始、结束扫描时间
			ProHandInSn sn = proHandInSnMapper.selectBeginEndScanTime(snTmp);
			
			ProHandIn upOb = new ProHandIn();
			upOb.setHandInNo(proHandInDto.getHandInNo());
			upOb.setScanTimeBegin(sn.getScanTimeBegin());
			upOb.setScanTimeEnd(sn.getScanTimeEnd());
//			0新建 1入库中 2入库完成
			upOb.setHandInStatus("2");
			upOb.setLastModifiedBy(proHandInDto.getLoginName());
			upOb.setGmtModified(now);
			
			proHandInMapper.updateByHandInNo(upOb);
		}
        
        return result;
	}
}
